package cn.lovemmd.model.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lovemmd.model.admin.common.PageResult;
import cn.lovemmd.model.admin.dto.ModelDTO;
import cn.lovemmd.model.admin.entity.Model;
import cn.lovemmd.model.admin.mapper.ModelMapper;
import cn.lovemmd.model.admin.service.ModelService;
import cn.lovemmd.model.admin.vo.ModelVO;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模型服务实现类
 * 
 * @author TLS
 * @since 2024-01-01
 */
@Service
@RequiredArgsConstructor
public class ModelServiceImpl extends ServiceImpl<ModelMapper, Model> implements ModelService {

    private static final Logger log = LoggerFactory.getLogger(ModelServiceImpl.class);

    @Override
    public PageResult<ModelVO> getModelPage(Long current, Long size, String search, String occupation) {
        // 创建分页对象
        Page<Model> page = new Page<>(current, size);
        
        // 构建查询条件
        LambdaQueryWrapper<Model> queryWrapper = new LambdaQueryWrapper<>();
        
        // 搜索条件
        if (StringUtils.hasText(search)) {
            queryWrapper.like(Model::getMName, search);
        }
        
        // 职业筛选
        if (StringUtils.hasText(occupation)) {
            queryWrapper.eq(Model::getMOccupation, occupation);
        }
        
        // 按创建时间倒序
        queryWrapper.orderByDesc(Model::getCreateTime);
        
        // 执行分页查询
        IPage<Model> modelPage = this.page(page, queryWrapper);
        
        // 转换为VO
        List<ModelVO> modelVOList = modelPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 返回分页结果
        return new PageResult<>(modelVOList, modelPage.getTotal(), modelPage.getCurrent(), modelPage.getSize());
    }

    @Override
    public ModelVO getModelById(Long id) {
        Model model = this.getById(id);
        return model != null ? convertToVO(model) : null;
    }

    @Override
    public boolean addModel(ModelDTO modelDTO) {
        Model model = new Model();
        // 手动映射字段
        model.setMId(modelDTO.getModelId());
        model.setMName(modelDTO.getModelName());
        model.setMOccupation(modelDTO.getModelOccupation());
        model.setMUrl(modelDTO.getModelUrl());
        model.setMImg(modelDTO.getModelImg());
        // 新增字段映射
        model.setMModelSource(modelDTO.getModelSource() != null ? modelDTO.getModelSource() : "游戏内提取");
        model.setMBoneBinding(modelDTO.getBoneBinding() != null ? modelDTO.getBoneBinding() : "已绑定");
        model.setMPhysicsBinding(modelDTO.getPhysicsBinding() != null ? modelDTO.getPhysicsBinding() : "已绑定");
        model.setMExpressionMaking(modelDTO.getExpressionMaking() != null ? modelDTO.getExpressionMaking() : "已制作");
        
        return this.save(model);
    }

    @Override
    public boolean updateModel(ModelDTO modelDTO) {
        if (modelDTO.getModelId() == null) {
            return false;
        }
        
        Model model = new Model();
        // 手动映射字段
        model.setMId(modelDTO.getModelId());
        model.setMName(modelDTO.getModelName());
        model.setMOccupation(modelDTO.getModelOccupation());
        model.setMUrl(modelDTO.getModelUrl());
        model.setMImg(modelDTO.getModelImg());
        // 新增字段映射
        model.setMModelSource(modelDTO.getModelSource() != null ? modelDTO.getModelSource() : "游戏内提取");
        model.setMBoneBinding(modelDTO.getBoneBinding() != null ? modelDTO.getBoneBinding() : "已绑定");
        model.setMPhysicsBinding(modelDTO.getPhysicsBinding() != null ? modelDTO.getPhysicsBinding() : "已绑定");
        model.setMExpressionMaking(modelDTO.getExpressionMaking() != null ? modelDTO.getExpressionMaking() : "已制作");
        
        return this.updateById(model);
    }

    @Override
    public boolean deleteModel(Long id) {
        return this.removeById(id);
    }

    @Override
    public boolean deleteBatchModels(List<Long> ids) {
        return this.removeByIds(ids);
    }

    @Override
    public Object getModelStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总模型数
        long totalCount = this.count();
        stats.put("total", totalCount);
        
        // 各职业模型数量
        List<Map<String, Object>> occupationStats = new ArrayList<>();
        String[] occupations = {"bladePoint", "Flame", "doubleGun", "machineGun", "guidedMissile", "sniper", "medic", "grenade", "engineer"};
        String[] occupationNames = {"刀锋", "烈焰", "双枪", "机枪", "导弹", "狙击", "医生", "榴弹", "工程师"};
        
        for (int i = 0; i < occupations.length; i++) {
            long count = this.count(new LambdaQueryWrapper<Model>()
                    .eq(Model::getMOccupation, occupations[i]));
            
            Map<String, Object> occupationStat = new HashMap<>();
            occupationStat.put("occupation", occupations[i]);
            occupationStat.put("name", occupationNames[i]);
            occupationStat.put("count", count);
            occupationStats.add(occupationStat);
        }
        
        stats.put("occupationStats", occupationStats);
        
        return stats;
    }

    @Override
    public List<Object> getOccupationList() {
        List<Object> occupationList = new ArrayList<>();
        
        String[] occupations = {"bladePoint", "Flame", "doubleGun", "machineGun", "guidedMissile", "sniper", "medic", "grenade", "engineer"};
        String[] occupationNames = {"刀锋", "烈焰", "双枪", "机枪", "导弹", "狙击", "医生", "榴弹", "工程师"};
        
        for (int i = 0; i < occupations.length; i++) {
            Map<String, Object> occupation = new HashMap<>();
            occupation.put("value", occupations[i]);
            occupation.put("label", occupationNames[i]);
            occupationList.add(occupation);
        }
        
        return occupationList;
    }

    @Override
    public List<Object> getModelIdList() {
        List<Object> modelIdList = new ArrayList<>();
        
        try {
            // 这里应该从数据库查询model_id表，暂时使用模拟数据
            // TODO: 实现数据库查询
            Map<String, Object> model1 = new HashMap<>();
            model1.put("m_id", 101011000);
            model1.put("m_name", "经典刀锋皮肤");
            model1.put("m_occupation", "bladePoint");
            modelIdList.add(model1);
            
            Map<String, Object> model2 = new HashMap<>();
            model2.put("m_id", 101011001);
            model2.put("m_name", "血腥玛丽");
            model2.put("m_occupation", "bladePoint");
            modelIdList.add(model2);
            
            Map<String, Object> model3 = new HashMap<>();
            model3.put("m_id", 101011002);
            model3.put("m_name", "王女艾琳");
            model3.put("m_occupation", "bladePoint");
            modelIdList.add(model3);
            
            Map<String, Object> model4 = new HashMap<>();
            model4.put("m_id", 101011003);
            model4.put("m_name", "捕猎少女欧丽莎");
            model4.put("m_occupation", "bladePoint");
            modelIdList.add(model4);
            
            Map<String, Object> model5 = new HashMap<>();
            model5.put("m_id", 101011004);
            model5.put("m_name", "炫彩之影·曼尼莎");
            model5.put("m_occupation", "bladePoint");
            modelIdList.add(model5);
            
            Map<String, Object> model6 = new HashMap<>();
            model6.put("m_id", 101011005);
            model6.put("m_name", "泳衣刀锋");
            model6.put("m_occupation", "bladePoint");
            modelIdList.add(model6);
            
            Map<String, Object> model7 = new HashMap<>();
            model7.put("m_id", 101011006);
            model7.put("m_name", "灵魂圣女·柯莉丝汀");
            model7.put("m_occupation", "bladePoint");
            modelIdList.add(model7);
            
            Map<String, Object> model8 = new HashMap<>();
            model8.put("m_id", 101011007);
            model8.put("m_name", "烈焰女皇");
            model8.put("m_occupation", "Flame");
            modelIdList.add(model8);
            
            Map<String, Object> model9 = new HashMap<>();
            model9.put("m_id", 101011008);
            model9.put("m_name", "火焰舞者");
            model9.put("m_occupation", "Flame");
            modelIdList.add(model9);
            
            Map<String, Object> model10 = new HashMap<>();
            model10.put("m_id", 101011009);
            model10.put("m_name", "双枪手");
            model10.put("m_occupation", "doubleGun");
            modelIdList.add(model10);
        } catch (Exception e) {
            log.error("获取model_id列表失败", e);
        }
        
        return modelIdList;
    }

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        // 获取操作系统类型
        String os = System.getProperty("os.name").toLowerCase();
        String uploadDir;
        
        if (os.contains("win")) {
            // Windows系统
            uploadDir = "c:\\model\\";
        } else {
            // Linux/Unix系统
            uploadDir = "/model/";
        }
        
        // 创建目录
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String uniqueId = UUID.randomUUID().toString().substring(0, 8);
        String newFilename = timestamp + "_" + uniqueId + fileExtension;
        
        // 保存文件
        Path filePath = uploadPath.resolve(newFilename);
        Files.copy(file.getInputStream(), filePath);
        
        log.info("文件上传成功: {}", filePath.toString());
        
        // 返回文件路径（用于前端访问）
        return filePath.toString();
    }

    /**
     * 将Model实体转换为ModelVO
     */
    private ModelVO convertToVO(Model model) {
        ModelVO vo = new ModelVO();
        // 手动映射字段
        vo.setMId(model.getMId());
        vo.setMName(model.getMName());
        vo.setMOccupation(model.getMOccupation());
        vo.setMUrl(model.getMUrl());
        vo.setMImg(model.getMImg());
        // 新增字段映射
        vo.setMModelSource(model.getMModelSource());
        vo.setMBoneBinding(model.getMBoneBinding());
        vo.setMPhysicsBinding(model.getMPhysicsBinding());
        vo.setMExpressionMaking(model.getMExpressionMaking());
        vo.setCreateTime(model.getCreateTime());
        vo.setUpdateTime(model.getUpdateTime());
        return vo;
    }
}
